﻿using System;
using System.Collections.Generic;
using System.Text;

using System.IO.Ports;
namespace Net
{
    /// <summary>
    /// 串口收发数据类
    /// </summary>
    public class SerialPort : INetProcess
    {
        System.IO.Ports.SerialPort sp;

        bool isOpen = false;

        public bool IsOpen
        {
            get { return isOpen; }
            set { isOpen = value; }
        }
        public SerialPort(string portName, int baudRate)
        {
            sp = new System.IO.Ports.SerialPort(portName, baudRate);
            try
            {
                Open();
            }
            catch
            { 
            
            }
        }

        public void Open()
        {
            if (!sp.IsOpen)
            {
                sp.Open();
            }
        }

        public int ReadTimeout
        {
            get { return sp.ReadTimeout; }
            set { sp.ReadTimeout = value; }
        }

        public string ReadLine()
        {
            return sp.ReadLine();
        }

        public int ReadByte()
        {
            return sp.ReadByte();
        }

        public int Read(byte[] buffer, int offset, int count)
        {
            return sp.Read(buffer, offset, count);
        }


        public void Write(string text)
        {
            sp.Write(text);
        }

        public void Write(byte[] buffer, int offset, int count)
        {
            sp.Write(buffer, offset, count);
        }


        public void WriteLine(string text)
        {
            sp.WriteLine(text);
        }

        public void DiscardInBuffer()
        {
            sp.DiscardInBuffer();
        }

        public void DiscardOutBuffer()
        {
            sp.DiscardOutBuffer();
        }

        public string CheckStatus()
        {
            throw new NotImplementedException();
        }


        #region INetProcess Members


        public event  EventHandler Disposed;

        public void Dispose()
        {
            sp.Close();
            //sp.Dispose();
        }

        #endregion
    }
}
